//
//  PublicityV2ViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/26.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "PublicityV2ViewController.h"

#import "StwxDetailViewController.h"
#import "OptionsPresentViewController.h"
#import "DocumentDetailViewController.h"

#import "PublicityListCell.h"

@interface PublicityV2ViewController ()

/// 模型视图
@property (nonatomic, readonly, strong) PublicityV2ViewModel* viewModel;

// UI

//IBOutlet
@property (nonatomic, weak) IBOutlet UIButton* publishBtn;
@property (nonatomic, weak) IBOutlet UIButton* typeBtn;
@property (nonatomic, weak) IBOutlet UILabel* typeLabel;
@property (nonatomic, weak) IBOutlet UITableView* currentTableView;

@end

@implementation PublicityV2ViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = UIColorHex(#f2f2f2);
    
    // hide sys navBar
    self.fd_prefersNavigationBarHidden = NO;
    // 去掉侧滑pop手势
    self.fd_interactivePopDisabled = YES;
    // create subViews
    [self _setupSubViews];
    // deal action
    [self _dealAction];
    // tableView auto rowHeight
    //    self.tableView.rowHeight = UITableViewAutomaticDimension;
    //    self.tableView.estimatedRowHeight = 100.0f;
    /// tableView rigister  cell
    [self.tableView mh_registerNibCell:[PublicityListCell class]];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
}

#pragma mark - Override
- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[viewDidLayoutSVSignal take:1] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    RAC(self.typeLabel, text) = [RACObserve(self.viewModel, typeName) doNext:^(id x)
    {
        @strongify(self);
        
        [self.typeBtn.superview setNeedsLayout];
    }];
    
    [[self.typeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self _presentOptionVC];
    }];
    
    self.viewModel.didSelectCommand = self.viewModel.selectCmd;
    
    [self.viewModel.selectCmd.executionSignals.switchToLatest subscribeNext:^(id x)
     {
         @strongify(self);
         
         ArticleListData* listData = x;
         
         if (listData.type == 2)
         {
             [self _push2DocumentDetailVC:listData.articleID];
         }
         else
         {
             [self _push2STWXDetailVC:listData.articleID];
         }
     }];
    
//    [[self.publishBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
//     {
//         @strongify(self);
//
//         [self _push2PublishVC];
//     }];
    
    [self.viewModel.moreCmd.executionSignals.switchToLatest subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSLog(@"Find index = %d", [x intValue]);
         
         [self _presentMore:[x intValue]];
     }];
    
    /// 删除操作
    [[self.viewModel.delCmd.executionSignals.switchToLatest deliverOnMainThread]
     subscribeNext:^(id x)
     {
         @strongify(self);
         [MBProgressHUD mh_hideHUD];
     }];
    [self.viewModel.delCmd.errors subscribeNext:^(NSError *error)
     {
         [MBProgressHUD mh_hideHUD];
         
         /// 处理验证错误的error
         if ([error.domain isEqualToString:SUCommandErrorDomain]) {
             [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
             return ;
         }
         [MBProgressHUD mh_showErrorTips:error];
     }];
}

- (UITableView*)customTableView
{
    return self.currentTableView;
}

#pragma mark - 更新初始化 操作
- (void)_setupSubViews
{
    
}

- (void)_setupAllView
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
}

#pragma mark - 事件处理
/// 事件处理
- (void)_dealAction
{
    @weakify(self);
    
}

#pragma mark - Delegate 一些无法用RAC实现
// UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

//// 下拉刷新
- (void)tableViewDidTriggerHeaderRefresh{
    /// 先调用父类的加载数据
    [super tableViewDidTriggerHeaderRefresh];
}
/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    return [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PublicityListCell class])];
}

/// config  data
- (void)configureCell:(PublicityListCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(PublicityListCellModel *)object
{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    [cell bindViewModel:object];
}

/// 文本内容区域
//- (UIEdgeInsets)contentInset
//{
//    return UIEdgeInsetsZero;
//}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
    /// 所以笔者采用实现计算好的cell的高度
    
    return [self.viewModel.dataSource[indexPath.row] cellHeight];
}

////////////////// 以下为UI代码，不必过多关注 ///////////////////
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* headerView = [[UIView alloc] init];
    headerView.backgroundColor = UIColorHex(#ffffff);
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView* footerView = [[UIView alloc] init];
    footerView.backgroundColor = UIColorHex(#ffffff);
    return footerView;
}

#pragma mark-代理方法
// 设立实现代理，注意要返回UIModalPresentationNone
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

#pragma mark - 功能

#pragma mark - 跳转
- (void)_presentMore:(NSInteger)dataIndex
{
    OptionsPresentViewController* vc = nil;
    
    @weakify(self);
    // 测试更多弹出
    OptionsPresentViewModel* vm = [[OptionsPresentViewModel alloc] initWithParams:@{}];
    vm.titles = self.viewModel.moreOptions;
    vm.topTitle = @"更多操作";
    vm.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                    {
                        @strongify(self);
                        
                        NSIndexPath* indexPath = input;
                        
                        if (indexPath.row == 0)
                        {
                            [MBProgressHUD mh_showProgressHUD:@""];
                            
                            [self.viewModel.delCmd execute:@(indexPath.row)];
                        }
                        
                        [[UIViewController getCurrentVC] dismissViewControllerAnimated:vc completion:^{
                            
                        }];
                        
                        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                            
                            [subscriber sendCompleted];
                            
                            return nil;
                        }];
                    }];
    vc = [[OptionsPresentViewController alloc] initWithViewModel:vm];
    vc.view.backgroundColor = [UIColor clearColor];
    //         vc.modalPresentationStyle = UIModalPresentationOverCurrentContext|UIModalPresentationFullScreen;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
        vc.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    }else{
        vc.modalPresentationStyle=UIModalPresentationCurrentContext;
    }
    [[UIViewController getCurrentVC] presentViewController:vc animated:YES completion:^
     {
         vc.view.backgroundColor = UIColorHex(#0000000f);
     }];
}

- (void)_push2STWXDetailVC:(NSString*)articleID
{
    StwxDetailViewModel* vm = [[StwxDetailViewModel alloc] initWithParams:@{}];
    //    [vm initStwxDetail:stwxDetailIVM];
    vm.articleID = articleID;
    StwxDetailViewController* vc = [[StwxDetailViewController alloc] initWithViewModel:vm];
    UIViewController* showVC = [UIViewController getCurrentVC];
    
    UINavigationController* navc = showVC.navigationController;
    [navc pushViewController:vc animated:YES];
}

- (void)_push2DocumentDetailVC:(NSString*)articleID
{
    DocumentDetailViewModel* vm = [[DocumentDetailViewModel alloc] initWithParams:@{}];
    //    [vm initStwxDetail:stwxDetailIVM];
    vm.articleID = articleID;
    DocumentDetailViewController* vc = [[DocumentDetailViewController alloc] initWithViewModel:vm];
    UIViewController* showVC = [UIViewController getCurrentVC];
    
    UINavigationController* navc = showVC.navigationController;
    [navc pushViewController:vc animated:YES];
}

- (void)_push2PublishVC
{
//    STWXPublishViewModel* vm = [[STWXPublishViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"生态文献"}];
//    STWXPublishViewController* vc = [[STWXPublishViewController alloc] initWithViewModel:vm];
//
//    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_presentOptionVC
{
    NSArray* types = self.viewModel.types;
    
    OptionsPresentViewController* vc = nil;
    
    @weakify(self);
    // 测试更多弹出
    OptionsPresentViewModel* vm = [[OptionsPresentViewModel alloc] initWithParams:@{}];
    vm.titles = [@[@"全部"] arrayByAddingObjectsFromArray:types];
    vm.topTitle = @"文件类型";
    vm.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                    {
                        @strongify(self);
                        
                        NSIndexPath* indexPath = input;
                        
                        // 选择
                        self.viewModel.chooseIndex = indexPath.row - 1;
                        
                        [[UIViewController getCurrentVC] dismissViewControllerAnimated:vc completion:^{
                            
                        }];
                        
                        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                            
                            [subscriber sendCompleted];
                            
                            return nil;
                        }];
                    }];
    vc = [[OptionsPresentViewController alloc] initWithViewModel:vm];
    vc.view.backgroundColor = [UIColor clearColor];
    //         vc.modalPresentationStyle = UIModalPresentationOverCurrentContext|UIModalPresentationFullScreen;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
        vc.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    }else{
        vc.modalPresentationStyle=UIModalPresentationCurrentContext;
    }
    [[UIViewController getCurrentVC] presentViewController:vc animated:YES completion:^
     {
         vc.view.backgroundColor = UIColorHex(#0000000f);
     }];
}

@end

